import React, {Component} from 'react'
import {
  NavBar,
  InputItem,
  Button,
  WingBlank,
  List,
  WhiteSpace,
  Radio,
} from 'antd-mobile'
import {connect} from 'react-redux'
import {Redirect} from 'react-router-dom'

import {register} from '../../redux/actions'
import Logo from '../../components/logo/logo'
import './register.less'

const ListItem = List.Item;

class Register extends Component {

  state = {
    username: '',
    password: '',
    confirm_password: '',
    type: '萌新'
  };

  register = () => {
    this.props.register(this.state);
  };

  handleChange = (name, val) => {
    // 更新对应状态
    this.setState({
      [name]: val
    })
  };

  toLogin = () => {
    this.props.history.replace('/login')
  };

  render() {
    const {type} = this.state;
    const {msg,redirectTo} = this.props.user;
    // 如果redirectTo有值，就需要重定向到指定的路由
    if(redirectTo){
      return <Redirect to={redirectTo}/>
    }

    return (
        <div>
          <NavBar>硅谷直聘</NavBar>
          <Logo/>
          <WingBlank>
            <List>
              {msg? <div className="error-msg">{msg}</div> : null}
              <WhiteSpace/>
              <InputItem placeholder="用户名" onChange={val => {
                this.handleChange('username', val)
              }}>用户名:</InputItem>
              <WhiteSpace/>
              <InputItem type="password" placeholder="密码" onChange={val => {
                this.handleChange('password', val)
              }}>密&nbsp;&nbsp;&nbsp;码:</InputItem>
              <WhiteSpace/>
              <InputItem type="password" placeholder="确认密码" onChange={val => {
                this.handleChange('confirm_password', val)
              }}>确认密码:</InputItem>
              <WhiteSpace/>
              <ListItem>
                <span>用户类型:</span>
                <Radio className="my-radio radio" checked={type === '萌新'}
                       onChange={() => this.handleChange('type', '萌新')}>萌新</Radio>
                <Radio className="my-radio radio" checked={type === '老板'}
                       onChange={() => this.handleChange('type', '老板')}>老板</Radio>
              </ListItem>
              <WhiteSpace/>
              <Button type="primary" onClick={this.register}>注册</Button>
              <Button onClick={this.toLogin}>已有账户</Button>
            </List>
          </WingBlank>
        </div>
    )
  }
}

export default connect(
    state => ({user:state.user}),
    {register}
)(Register)